/**
 * 用户管理的用户列表界面。
 * @author linzongxue
 * @create_date 2012-1-30
 */
define(function(){
	var UserGridPanel = Ext.extend(Ext.grid.GridPanel, {
		border: false,
		stripeRows: true,
	    enableHdMenu: false,
	    //autoExpandColumn: 3,
	    loadMask: {msg: '正在加载数据...'},
		initComponent: function(){
			var store = new Ext.data.JsonStore({
			    remoteSort: true, 
			    root: 'result', totalProperty: 'totalItems', idProperty: 'id',
			    fields: ['loginName', 'name', 'position', 'departName', 'gender', 'isAdmin'],
			    url: 'sys/user/query.do'
			});
			UserGridPanel.superclass.initComponent.call(Ext.apply(this, {
				tbar: this.createTbar(),
				store: store,
				columns: [
					new Ext.grid.RowNumberer(),
				    this.sm = new Ext.grid.CheckboxSelectionModel(),
					{header: '账号', width: 120, dataIndex: 'loginName'},
					{header: '姓名', width: 100, dataIndex: 'name'},
					{header: '机构', width: 150, dataIndex: 'departName'},
					{header: '性别', width: 50, dataIndex: 'gender', renderer: this.renderGender},
					{header: '岗位', width: 120, dataIndex: 'position'}
				],
				bbar: cu.createPagingBar(store)
			}));
			this.on({
				afterrender: function(){
					store.load();
				},
				dblclick: function(){
					if(au.permit('sys.user.modify')) this.modifyUser();
				}
			});
			this.getSelectionModel().on({
				rowselect: function(sm, i, record){
					//不要直接用record.json，避免名字被修改后不更新
					this.ownerCt.changeUser({id:record.id, name:record.get('name')});
				},
				rowdeselect: function(sm, i, record){
					if (sm.getSelections().length == 0){
						this.ownerCt.changeUser(null);
					}
				},
				scope: this
			});
		},
		queryUsers: function(){
			var baseParams = this.store.baseParams;
			this.getTopToolbar().cascade(function(c){
				if (!c.name || !c.getValue) return;
				c.getValue() ? baseParams[c.name] = c.getValue() : delete baseParams[c.name];
			});
			this.getStore().load();
		},
		refresh: function(){
			this.getTopToolbar().cascade(function(c){
				if(c.name) c.setValue(null);
			});
			this.queryUsers();
		},
		addUser: function(){
			use('sys.user.UserWindow', function(Win){
				new Win({
					title: '添加用户',
					callback: function(data){
						this.queryUsers();
					},
					cbScope: this
				}).show();
			}, this);
		},
		modifyUser: function(){
			var record = this.getSelectionModel().getSelected();
			if (!record){
				cu.hint('请选择要修改的用户');
				return;
			}
			if (record.get('isAdmin')){
				cu.alert('不能修改“{0}”账号'.f(record.get('name')));
				return ;
			}
			use('sys.user.UserWindow', function(Win){
				new Win({
					title: '修改用户',
					modifiedId: record.id,
					callback: function(data){
						var oldName = record.get('name');
						for(var p in data){record.set(p, data[p]);}
						record.commit(); //去除单元格中的修改标记
						if (oldName !== data.name){
							this.ownerCt.changeUser(data); //更新关联角色的显示
						}
					},
					cbScope: this
				}).show();
			}, this);
		},
		removeUsers: function(){
			var records = this.getSelectionModel().getSelections();
			if (records.length == 0){
				cu.hint('请选择要删除的用户');
				return;
			}
			for (var i = 0; i < records.length; i ++){
				if (records[i].get('isAdmin')){
					cu.alert('不能删除“{0}”账号'.f(records[i].get('name')));
					return;
				}
			}
			var msg = '确定要删除选中的{0}个用户吗？'.f(records.length);
			cu.confirm(msg, function(){
				cu.post({
					url: 'sys/user/delete.do',
					params: {ids: lu.pluck(records, 'id')},
					success: function(){
						this.queryUsers();
					},
					scope: this
				});
			}, this);
		},
		createTbar: function(){
			return new Ext.Toolbar({
				items: au.permit([
					{text: '添加', permitId:'sys.user.add', handler: this.addUser, iconCls: 'icon-add',scope: this, tooltip:'添加用户'},
				    {text: '修改', permitId:'sys.user.modify', handler: this.modifyUser, iconCls: 'icon-edit',scope: this, tooltip:'修改用户'},
				    {text: '删除', permitId:'sys.user.remove', handler: this.removeUsers, iconCls: 'icon-delete',scope: this, tooltip:'删除用户'},
				    '->',
				    {text: '所属机构：', xtype: 'label'},
				    {
						xtype:'combotree',
						name: 'departId',
						width: 120,
						listWidth: 200,
						dataUrl: 'sys/depart/getDepartTreeData.do?',
						nodePathUrl: 'sys/util/getEntityAttrPath.do?c=sys.entity.Department',
						root: {id:'root', text:'/', expanded: true},
						rootVisible: true,
						rootSelectable: true,
						rootValue: null
			        },
				    {text: '账号：', xtype: 'label', style:'margin-left:5px;'},
				    {xtype: 'textfield', name: 'loginName', width: 70},
				    {text: '姓名：', xtype: 'label', style:'margin-left:5px;'},
				    {xtype: 'textfield', name: 'name', width: 70},
			        {handler: this.queryUsers, scope: this, iconCls:'icon-find', tooltip:'查找用户'},
			        {handler: this.refresh, scope: this, iconCls:'icon-refresh', tooltip:'清空查询条件并刷新'},
			        '-'
				]),
				listeners: {
					afterrender: function(){
						//绑定回车事件
						cu.bindEnter(this, function(){
							this.ownerCt.queryUsers();
						}, this);
					}
				}
			});
		},
		renderGender: function(value){
			return value ? au.getDictText('gender', value) : '';
		}
	});
	return UserGridPanel;
});